package edu.nju.mutest.util;

import com.github.javaparser.JavaParser;
import com.github.javaparser.ParserConfiguration;
import com.github.javaparser.StaticJavaParser;
import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.symbolsolver.JavaSymbolSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver;
import com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Optional;

public class CompilationUnitUtil {

    // ParserConfiguration for type resolution.
    public static final ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(
            new JavaSymbolSolver(
                    new CombinedTypeSolver(
                            new ReflectionTypeSolver()
                    )
            )
    );

    /**
     * Alternative version of {@link StaticJavaParser#parse(File)} with different ParserConfiguration
     */
    public static Optional<CompilationUnit> parse(File srcFile) throws FileNotFoundException {
        return new JavaParser(parserConfiguration).parse(srcFile).getResult();
    }

    /**
     * Alternative version of {@link StaticJavaParser#parse(String)} with different ParserConfiguration
     */
    public static Optional<CompilationUnit> parse(String srcString) {
        return new JavaParser(parserConfiguration).parse(srcString).getResult();
    }

    /**
     * Try to clone {@link CompilationUnit} with {@link CompilationUnitUtil#parserConfiguration}, call
     * {@link CompilationUnit#clone()} if failed.
     *
     * @param orig origin {@link CompilationUnit}
     * @return copied {@link CompilationUnit}
     */
    public static CompilationUnit clone(CompilationUnit orig) {
        Optional<CompilationUnit> newCU = parse(orig.toString());
        return newCU.orElseGet(orig::clone);
    }
}
